// 实时同步调试工具
class SyncDebugger {
  constructor() {
    this.logs = []
    this.maxLogs = 100
    this.isEnabled = true
  }

  // 启用/禁用调试
  enable() {
    this.isEnabled = true
    console.log('🔧 同步调试器已启用')
  }

  disable() {
    this.isEnabled = false
    console.log('🔧 同步调试器已禁用')
  }

  // 添加日志
  log(type, message, data = null) {
    if (!this.isEnabled) return

    const logEntry = {
      id: Date.now() + Math.random(),
      timestamp: new Date(),
      type,
      message,
      data
    }

    this.logs.push(logEntry)

    // 限制日志数量
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }

    // 控制台输出
    const prefix = this.getLogPrefix(type)
    console.log(`${prefix} ${message}`, data || '')

    return logEntry
  }

  // 获取日志前缀
  getLogPrefix(type) {
    const prefixes = {
      info: 'ℹ️',
      success: '✅',
      warning: '⚠️',
      error: '❌',
      debug: '🐛',
      sync: '🔄',
      network: '🌐'
    }
    return prefixes[type] || '📝'
  }

  // 记录连接事件
  logConnection(event, data) {
    this.log('network', `连接事件: ${event}`, data)
  }

  // 记录涂色动作
  logPaintAction(action, data) {
    this.log('sync', `涂色动作: ${action}`, data)
  }

  // 记录消息发送
  logMessageSent(messageType, data) {
    this.log('network', `发送消息: ${messageType}`, data)
  }

  // 记录消息接收
  logMessageReceived(messageType, data) {
    this.log('network', `接收消息: ${messageType}`, data)
  }

  // 记录错误
  logError(error, context = '') {
    this.log('error', `错误: ${error.message}`, {
      error: error.toString(),
      stack: error.stack,
      context
    })
  }

  // 记录性能数据
  logPerformance(operation, duration, data = {}) {
    this.log('debug', `性能: ${operation} (${duration}ms)`, data)
  }

  // 获取所有日志
  getLogs() {
    return [...this.logs]
  }

  // 获取特定类型的日志
  getLogsByType(type) {
    return this.logs.filter(log => log.type === type)
  }

  // 获取最近的日志
  getRecentLogs(count = 10) {
    return this.logs.slice(-count)
  }

  // 清空日志
  clearLogs() {
    this.logs = []
    console.log('🔧 日志已清空')
  }

  // 导出日志
  exportLogs() {
    const data = {
      timestamp: new Date().toISOString(),
      logs: this.logs,
      summary: this.getSummary()
    }

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `sync-debug-logs-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`
    link.click()
    URL.revokeObjectURL(url)

    this.log('info', '日志已导出')
  }

  // 获取摘要
  getSummary() {
    const summary = {
      totalLogs: this.logs.length,
      byType: {},
      timeRange: null
    }

    if (this.logs.length > 0) {
      summary.timeRange = {
        start: this.logs[0].timestamp,
        end: this.logs[this.logs.length - 1].timestamp
      }
    }

    // 按类型统计
    this.logs.forEach(log => {
      summary.byType[log.type] = (summary.byType[log.type] || 0) + 1
    })

    return summary
  }

  // 检查连接状态
  checkConnectionStatus(signalRService) {
    const status = {
      isConnected: signalRService.getConnectionStatus(),
      connectionId: signalRService.getConnectionId(),
      messageQueue: signalRService.getMessageQueueStatus()
    }

    this.log('debug', '连接状态检查', status)
    return status
  }

  // 检查画布状态
  checkCanvasStatus(canvasRef) {
    if (!canvasRef.value) {
      this.log('warning', '画布引用不可用')
      return null
    }

    const canvas = canvasRef.value
    const ctx = canvas.getContext('2d')
    
    const status = {
      width: canvas.width,
      height: canvas.height,
      hasContext: !!ctx,
      contextState: ctx ? {
        fillStyle: ctx.fillStyle,
        strokeStyle: ctx.strokeStyle,
        lineWidth: ctx.lineWidth
      } : null
    }

    this.log('debug', '画布状态检查', status)
    return status
  }

  // 模拟网络延迟
  simulateNetworkDelay(delay = 1000) {
    this.log('warning', `模拟网络延迟: ${delay}ms`)
    return new Promise(resolve => setTimeout(resolve, delay))
  }

  // 模拟网络断开
  simulateNetworkDisconnect(signalRService) {
    this.log('warning', '模拟网络断开')
    return signalRService.disconnect()
  }

  // 性能监控
  startPerformanceMonitor() {
    this.log('debug', '开始性能监控')
    
    // 监控内存使用
    if (performance.memory) {
      setInterval(() => {
        const memory = performance.memory
        this.log('debug', '内存使用', {
          used: Math.round(memory.usedJSHeapSize / 1024 / 1024) + 'MB',
          total: Math.round(memory.totalJSHeapSize / 1024 / 1024) + 'MB',
          limit: Math.round(memory.jsHeapSizeLimit / 1024 / 1024) + 'MB'
        })
      }, 10000)
    }

    // 监控帧率
    let frameCount = 0
    let lastTime = performance.now()
    
    const countFrames = () => {
      frameCount++
      const currentTime = performance.now()
      
      if (currentTime - lastTime >= 1000) {
        const fps = Math.round((frameCount * 1000) / (currentTime - lastTime))
        this.log('debug', `帧率: ${fps} FPS`)
        frameCount = 0
        lastTime = currentTime
      }
      
      requestAnimationFrame(countFrames)
    }
    
    requestAnimationFrame(countFrames)
  }

  // 创建调试面板
  createDebugPanel() {
    const panel = document.createElement('div')
    panel.id = 'sync-debug-panel'
    panel.style.cssText = `
      position: fixed;
      top: 10px;
      right: 10px;
      width: 300px;
      max-height: 400px;
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 10px;
      border-radius: 8px;
      font-family: monospace;
      font-size: 12px;
      z-index: 10000;
      overflow-y: auto;
    `

    const title = document.createElement('div')
    title.textContent = '🔄 同步调试器'
    title.style.cssText = 'font-weight: bold; margin-bottom: 10px; border-bottom: 1px solid #666; padding-bottom: 5px;'
    panel.appendChild(title)

    const controls = document.createElement('div')
    controls.style.cssText = 'margin-bottom: 10px;'
    
    const clearBtn = document.createElement('button')
    clearBtn.textContent = '清空'
    clearBtn.onclick = () => this.clearLogs()
    clearBtn.style.cssText = 'margin-right: 5px; padding: 2px 8px; font-size: 10px;'
    
    const exportBtn = document.createElement('button')
    exportBtn.textContent = '导出'
    exportBtn.onclick = () => this.exportLogs()
    exportBtn.style.cssText = 'margin-right: 5px; padding: 2px 8px; font-size: 10px;'
    
    const toggleBtn = document.createElement('button')
    toggleBtn.textContent = this.isEnabled ? '禁用' : '启用'
    toggleBtn.onclick = () => {
      if (this.isEnabled) {
        this.disable()
        toggleBtn.textContent = '启用'
      } else {
        this.enable()
        toggleBtn.textContent = '禁用'
      }
    }
    toggleBtn.style.cssText = 'padding: 2px 8px; font-size: 10px;'
    
    controls.appendChild(clearBtn)
    controls.appendChild(exportBtn)
    controls.appendChild(toggleBtn)
    panel.appendChild(controls)

    const logContainer = document.createElement('div')
    logContainer.id = 'sync-debug-logs'
    panel.appendChild(logContainer)

    document.body.appendChild(panel)
    this.updateDebugPanel()
  }

  // 更新调试面板
  updateDebugPanel() {
    const logContainer = document.getElementById('sync-debug-logs')
    if (!logContainer) return

    const recentLogs = this.getRecentLogs(10)
    logContainer.innerHTML = recentLogs.map(log => {
      const time = log.timestamp.toLocaleTimeString()
      const prefix = this.getLogPrefix(log.type)
      return `<div style="margin-bottom: 2px; font-size: 10px;">
        <span style="color: #ccc;">${time}</span>
        <span>${prefix} ${log.message}</span>
      </div>`
    }).join('')
  }
}

// 创建全局调试器实例
const syncDebugger = new SyncDebugger()

// 在开发环境下自动启用
if (process.env.NODE_ENV === 'development') {
  syncDebugger.enable()
  syncDebugger.createDebugPanel()
  
  // 定期更新面板
  setInterval(() => {
    syncDebugger.updateDebugPanel()
  }, 1000)
}

export default syncDebugger
